package com.choose.seat.modules.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.choose.seat.common.constants.FigureConstants;
import com.choose.seat.common.controller.BaseController;
import com.choose.seat.common.utils.R;
import com.choose.seat.modules.domain.CinemaActivity;
import com.choose.seat.modules.domain.CinemaSeat;
import com.choose.seat.modules.domain.Release;
import com.choose.seat.modules.domain.Statistics;
import com.choose.seat.modules.service.CinemaActivityService;
import com.choose.seat.modules.service.CinemaSeatService;
import com.choose.seat.modules.service.CinemaUserService;
import com.choose.seat.system.domain.UserDO;
import com.choose.seat.system.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yangpingming
 * @version 1.0
 * @description
 * @date 11/8/2023 9:50 AM
 */
@Controller
@RequestMapping
public class TrpActivityController extends BaseController {

    @Autowired
    private CinemaActivityService cinemaActivityService;
    @Autowired
    private CinemaUserService cinemaUserService;
    @Autowired
    private CinemaSeatService cinemaSeatService;
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/dologin", method = RequestMethod.GET)
    @ResponseBody
    public UserDO doLogin(HttpServletRequest request) {
        Long user_id=Long.valueOf(request.getParameter("youId"));

        UserDO userDO=userService.getOne(user_id);


        return userDO;
    }

    @GetMapping("/release")
    @ResponseBody
    public List<Release> list(@RequestParam String youId) {

        List<CinemaActivity> cinemaActivityList = new ArrayList<>();
        if(StringUtils.isNotEmpty(youId)){
            QueryWrapper<CinemaActivity> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(CinemaActivity::getCreatePerson,youId);
            cinemaActivityList = cinemaActivityService.list(queryWrapper);
        }else{
            cinemaActivityList = cinemaActivityService.list();
        }

        List<Release> releaseList=new ArrayList<>();
        for(CinemaActivity cinemaActivity:cinemaActivityList){
            if(Objects.nonNull(cinemaActivity.getActivityId())){
                Release release=new Release();
                release.setId(Objects.nonNull(cinemaActivity.getActivityId() )?cinemaActivity.getActivityId(): FigureConstants.ZERO);
                release.setName((StringUtils.isNotEmpty(cinemaActivity.getActivityName()) )?cinemaActivity.getActivityName():FigureConstants.STR_ZERO);
                release.setPictureUrl( (StringUtils.isNotEmpty(cinemaActivity.getPictureUrl()) )?cinemaActivity.getPictureUrl():FigureConstants.STR_ZERO );

                SimpleDateFormat simpleDateFormatDate= new SimpleDateFormat("yyyy-MM-dd");
                String activityDate = simpleDateFormatDate.format(cinemaActivity.getActivityDateTime());
                release.setDate(activityDate);

                SimpleDateFormat simpleDateFormatHourMinute = new SimpleDateFormat("hh-mm");
                String beginTime =simpleDateFormatHourMinute.format(cinemaActivity.getBegainTime());
                release.setUptime_time(beginTime);
                String endTime= simpleDateFormatHourMinute.format(cinemaActivity.getEndTime());
                release.setDeadline_time(endTime);
                release.setRemark( (StringUtils.isNotEmpty(cinemaActivity.getRemark()) )?cinemaActivity.getRemark():FigureConstants.STR_ZERO );
                release.setChange( (Objects.nonNull(cinemaActivity.getIsModify() )?cinemaActivity.getIsModify(): FigureConstants.ZERO));
                release.setLocation( (StringUtils.isNotEmpty(cinemaActivity.getCinemaHallName()))?cinemaActivity.getCinemaHallName():FigureConstants.STR_ZERO );
                release.setMy_id( (StringUtils.isNotEmpty(cinemaActivity.getCreatePerson()))?cinemaActivity.getCreatePerson():getUsername() );
                releaseList.add(release);
            }

        }
        return  releaseList;
    }

    @GetMapping(value = "/addactivity")
    @ResponseBody
    public R saveActivity(HttpServletRequest request){
        DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date =new Date() ;
        CinemaActivity cinemaActivity=new CinemaActivity();

        cinemaActivity.setPictureUrl(StringUtils.isNotEmpty(request.getParameter("pictureUrl"))?request.getParameter("pictureUrl"):FigureConstants.STR_ZERO);
        cinemaActivity.setActivityName(StringUtils.isNotEmpty(request.getParameter("movieName"))?request.getParameter("movieName"):FigureConstants.STR_ZERO);

        cinemaActivity.setBegainTime(new Date());
        if(StringUtils.isNotEmpty(request.getParameter("movie_deadtime"))){
            try {
                 date = DateUtils.parseDate(request.getParameter("movie_deadtime"),"yyyy-MM-dd");
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }else{
             date =new Date(date.getTime()+(1000*60*60*24*30));
        }
        cinemaActivity.setEndTime(date);
        /*cinemaActivity.setCinemaHallId();*/
        cinemaActivity.setCinemaHallName(StringUtils.isNotEmpty(request.getParameter("location"))?request.getParameter("location"):FigureConstants.STR_ZERO);

        if(StringUtils.isNotEmpty(request.getParameter("change"))){
            String change =request.getParameter("change");
            if(change.equals("true")){
                cinemaActivity.setIsModify(1);
            }else{
                cinemaActivity.setIsModify(0);
            }
        }else{
            cinemaActivity.setIsPositive(1);
        }
        cinemaActivity.setIsPositive(FigureConstants.ONE);
        cinemaActivity.setRemark(StringUtils.isNotEmpty(request.getParameter("remark"))?request.getParameter("remark"):FigureConstants.STR_ZERO);
        cinemaActivity.setCreatePerson(StringUtils.isNotEmpty(request.getParameter("you_id"))?request.getParameter("you_id"):getUsername());
        cinemaActivity.setCreateTime(new Date());
        cinemaActivity.setUpdateTime(new Date());
        if(cinemaActivityService.save(cinemaActivity)){
            return R.ok();
        }else{
            return R.error();
        }
    }


    @RequestMapping(value = "/statistics", method = RequestMethod.GET)
    @ResponseBody
    public Statistics statistics(HttpServletRequest request) {
        Statistics statistics = new Statistics();
        String activityId = request.getParameter("movieId");
        if(StringUtils.isNotEmpty(activityId)){
           QueryWrapper<CinemaSeat> seatQueryWrapper = new QueryWrapper();
           seatQueryWrapper.eq("isDelete",FigureConstants.ZERO);
           seatQueryWrapper.last("and cinemaHallId in (select cinemaHallId from cinema_hall where cinemaHallId in (select cinemaHallId from cinema_activity where activityId="+activityId+") )" );
           List<CinemaSeat> cinemaSeatList=cinemaSeatService.list(seatQueryWrapper);
           int summary=cinemaSeatList.size();
           Map<Integer,Long> activeMap =cinemaSeatList.stream().collect(Collectors.groupingBy(CinemaSeat::getIsActive,Collectors.counting()));
           statistics.setSum(summary);
           statistics.setNot_checked(Math.toIntExact(activeMap.get(0)));
           statistics.setChecked(summary-Math.toIntExact(activeMap.get(0)));

        }else{
            statistics.setSum(100);
            statistics.setChecked(0);
            statistics.setNot_checked(100);
        }
        return statistics;

    }



    @GetMapping("/attend")
    @ResponseBody
    public List<Release> attend(@RequestParam String you_id) {

        List<CinemaActivity> cinemaActivityList = new ArrayList<>();
        if(StringUtils.isNotEmpty(you_id)){
            QueryWrapper<CinemaActivity> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(CinemaActivity::getCreatePerson,you_id);
            cinemaActivityList = cinemaActivityService.list(queryWrapper);
        }else{
            cinemaActivityList = cinemaActivityService.list();
        }

        List<Release> releaseList=new ArrayList<>();
        for(CinemaActivity cinemaActivity:cinemaActivityList){
            if(Objects.nonNull(cinemaActivity.getActivityId())){
                Release release=new Release();
                release.setId(Objects.nonNull(cinemaActivity.getActivityId() )?cinemaActivity.getActivityId(): FigureConstants.ZERO);
                release.setName((StringUtils.isNotEmpty(cinemaActivity.getActivityName()) )?cinemaActivity.getActivityName():FigureConstants.STR_ZERO);
                release.setPictureUrl( (StringUtils.isNotEmpty(cinemaActivity.getPictureUrl()) )?cinemaActivity.getPictureUrl():FigureConstants.STR_ZERO );
                release.setDate( (Objects.nonNull(cinemaActivity.getActivityDateTime()) )?cinemaActivity.getActivityDateTime().toString():FigureConstants.STR_ZERO );
                release.setRemark( (StringUtils.isNotEmpty(cinemaActivity.getRemark()) )?cinemaActivity.getRemark():FigureConstants.STR_ZERO );
                release.setChange( (Objects.nonNull(cinemaActivity.getIsModify() )?cinemaActivity.getIsModify(): FigureConstants.ZERO));
                release.setLocation( (StringUtils.isNotEmpty(cinemaActivity.getCinemaHallName()))?cinemaActivity.getCinemaHallName():FigureConstants.STR_ZERO );
                release.setMy_id( (StringUtils.isNotEmpty(cinemaActivity.getCreatePerson()))?cinemaActivity.getCreatePerson():getUsername() );
                releaseList.add(release);
            }

        }
        return  releaseList;
    }

    @GetMapping(value = "/attendList")
    @ResponseBody
    public Release attendList(HttpServletRequest request) {
        Release release=new Release();
        if(StringUtils.isNotEmpty(request.getParameter("movieId"))){
            QueryWrapper<CinemaActivity> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(CinemaActivity::getActivityId,request.getParameter("movieId"));
            CinemaActivity cinemaActivity=cinemaActivityService.getOne(queryWrapper);

            release.setId(Objects.nonNull(cinemaActivity.getActivityId() )?cinemaActivity.getActivityId(): FigureConstants.ZERO);
            release.setName((StringUtils.isNotEmpty(cinemaActivity.getActivityName()) )?cinemaActivity.getActivityName():FigureConstants.STR_ZERO);
            release.setPictureUrl( (StringUtils.isNotEmpty(cinemaActivity.getPictureUrl()) )?cinemaActivity.getPictureUrl():FigureConstants.STR_ZERO );

            SimpleDateFormat simpleDateFormatDate= new SimpleDateFormat("yyyy-MM-dd");
            String activityDate = simpleDateFormatDate.format(cinemaActivity.getActivityDateTime());
            release.setDate(activityDate);

            SimpleDateFormat simpleDateFormatHourMinute = new SimpleDateFormat("hh-mm");
            String beginTime =simpleDateFormatHourMinute.format(cinemaActivity.getBegainTime());
            release.setUptime_time(beginTime);
            String endTime= simpleDateFormatHourMinute.format(cinemaActivity.getEndTime());
            release.setDeadline_time(endTime);
            release.setRemark( (StringUtils.isNotEmpty(cinemaActivity.getRemark()) )?cinemaActivity.getRemark():FigureConstants.STR_ZERO );
            release.setChange( (Objects.nonNull(cinemaActivity.getIsModify() )?cinemaActivity.getIsModify(): FigureConstants.ZERO));
            release.setLocation( (StringUtils.isNotEmpty(cinemaActivity.getCinemaHallName()))?cinemaActivity.getCinemaHallName():FigureConstants.STR_ZERO );
            release.setMy_id( (StringUtils.isNotEmpty(cinemaActivity.getCreatePerson()))?cinemaActivity.getCreatePerson():getUsername() );
        }
        return release;
    }


    @GetMapping(value = "/getSeat")
    @ResponseBody
    public List<CinemaSeat> getSeat(HttpServletRequest request) {
        QueryWrapper<CinemaSeat> queryWrapper= new QueryWrapper();
        if(StringUtils.isNotEmpty(request.getParameter("hallId"))){
            queryWrapper.eq("cinemaHallId",Integer.valueOf(request.getParameter("hallId")));
            return cinemaSeatService.list(queryWrapper);
        }else{
            queryWrapper.eq("cinemaHallId",1);
            return cinemaSeatService.list(queryWrapper);
        }
    }

    @GetMapping(value = "/chooseSeat")
    @ResponseBody
    public R chooseSeat(HttpServletRequest request) {
        if (StringUtils.isNotEmpty(request.getParameter("hallId"))) {
            Integer hallId = Integer.valueOf(request.getParameter("hallId"));
            if (StringUtils.isNotEmpty(request.getParameter("x"))) {
                Integer x = Integer.valueOf(request.getParameter("x"));
                if (StringUtils.isNotEmpty(request.getParameter("y"))) {
                    Integer y = Integer.valueOf(request.getParameter("y"));
                    QueryWrapper<CinemaSeat> queryWrapper = new QueryWrapper();
                    queryWrapper.lambda().
                            eq(CinemaSeat::getSeatX, x).
                            eq(CinemaSeat::getSeatY, y).
                            eq(CinemaSeat::getCinemaHallId, hallId);
                    CinemaSeat cinemaSeat = cinemaSeatService.getOne(queryWrapper);
                    cinemaSeat.setIsActive(FigureConstants.ONE);
                    if (cinemaSeatService.save(cinemaSeat)) {
                        R.ok();
                    } else {
                        R.error();
                    }

                }
            }

        }

        return R.ok("影厅的位置信息不存在");

    }











    @PostMapping("/release/save")
    @ResponseBody
    public R save(CinemaActivity cinemaActivity){
        cinemaActivity.setCreatePerson(getUsername());
        cinemaActivity.setCreateTime(new Date());
        if(cinemaActivityService.save(cinemaActivity)){
            return R.ok();
        }else{
            return R.error();
        }

    }

    @PostMapping("/release/edit")
    @ResponseBody
    public CinemaActivity edit(Long id){

        CinemaActivity cinemaActivity= cinemaActivityService.getById(id);
        return cinemaActivity;
    }

    @PostMapping("/release/delete")
    @ResponseBody
    public R delete(Long id){
        if(cinemaActivityService.removeById(id)){
            return R.ok();
        }else{
            return R.error();
        }

    }

    @PostMapping("/release/batchRemoves")
    @ResponseBody
    public R batchRemove(Long [] ids){
        if(cinemaActivityService.removeBatchByIds(Arrays.asList(ids))){
            return R.ok();
        }else{
            return R.error();
        }

    }



}
